package com.ilop.sthome.ui.activity.mine;

import android.content.Intent;
import android.net.Uri;
import androidx.annotation.NonNull;
import android.text.TextUtils;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.request.RequestOptions;
import com.ilop.sthome.ui.activity.main.ContainLoginActivity;
import com.example.common.utils.LiveDataBus;
import com.example.common.view.imagePicker.ImagePicker;
import com.example.common.view.imagePicker.cropper.CropImage;
import com.example.common.view.imagePicker.cropper.CropImageView;
import com.ilop.sthome.common.CommonId;
import com.ilop.sthome.mvp.contract.mine.PersonalContract;
import com.ilop.sthome.mvp.present.mine.PersonalPresenter;
import com.ilop.sthome.ui.dialog.ChooseImageDialog;
import com.ilop.sthome.utils.tools.FileUtil;
import com.siterwell.familywellplus.R;
import com.siterwell.familywellplus.databinding.ActivityHeadPortraitBinding;

import java.io.File;

/**
 * @author skygge
 * @date 2020/5/16.
 * GitHub：javofxu@github.com
 * email：skygge@yeah.net
 * description：头像展示和修改界面
 */
public class HeadPortraitActivity extends ContainLoginActivity<PersonalPresenter, ActivityHeadPortraitBinding> implements PersonalContract.IView {

    private String mNickname = "";
    private String mPhone= "";
    private String mEmail= "";
    private String mHeadPath;
    private boolean isPersonal;
    private File mFile;
    private ImagePicker mImagePicker;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_head_portrait;
    }

    @Override
    protected void initialize() {
        super.initialize();
        immersionStatusBar(false);
        isPersonal = getIntent().getBooleanExtra(CommonId.KEY_MODIFY, false);
    }

    @Override
    protected void initPresent() {
        super.initPresent();
        mPresent = new PersonalPresenter(mContext);
    }

    @Override
    protected void initView() {
        super.initView();
        mImagePicker = new ImagePicker();
        mImagePicker.setCropImage(true);
    }

    @Override
    protected void initData() {
        super.initData();
        mPresent.getUserInfo();
        LiveDataBus.get().with(CommonId.UPLOAD_IMAGE_SUCCESS, String.class).observe(this, s -> {
            this.mHeadPath = s;
            mPresent.onSaveUserInfo(mNickname, mPhone, mEmail, s);
        });
    }

    @Override
    protected void initListener() {
        super.initListener();
        mDBind.ivHeadBack.setOnClickListener(v -> finish());
        mDBind.ivHeadMore.setOnClickListener(v -> startChooser());
        mDBind.ivHead.setOnLongClickListener(v -> {
            startChooser();
            return true;
        });
    }

    @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        mImagePicker.onActivityResult(this, requestCode, resultCode, data);
    }

    @Override public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions,
                                                     @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        mImagePicker.onRequestPermissionsResult(this, requestCode, permissions, grantResults);
    }

    @Override
    public void showNickName(String nickname) {
        this.mNickname = nickname;
    }

    @Override
    public void showPhone(String phone) {
        this.mPhone = phone;
    }

    @Override
    public void showEmail(String email) {
        this.mEmail = email;
    }

    @Override
    public void showUserImg(String path) {
        //关闭内存缓存和磁盘缓存
        RequestOptions mOptions = new RequestOptions().skipMemoryCache(true).diskCacheStrategy(DiskCacheStrategy.NONE);
        if (!TextUtils.isEmpty(path)){
            Glide.with(mContext)
                    .load(path)
                    .apply(mOptions)
                    .into(mDBind.ivHead);
        }else {
            Glide.with(mContext)
                    .load(R.mipmap.head_open)
                    .apply(mOptions)
                    .into(mDBind.ivHead);
        }
    }

    @Override
    public void showToastMsg(String msg) {
        dismissProgressDialog();
        showToast(msg);
    }

    @Override
    public void finishActivity() {
        if (isPersonal && !TextUtils.isEmpty(mHeadPath)){
            LiveDataBus.get().with(CommonId.KEY_LOGIN_ID).setValue(mHeadPath);
        }
    }

    private void startChooser() {
        ChooseImageDialog mDialog = new ChooseImageDialog(mContext, new ChooseImageDialog.onChooseCallBack() {
            @Override
            public void startGallery() {
                startGalleryToGetImg();
            }

            @Override
            public void startCamera() {
                startCameraToGetImg();
            }
        });
        mDialog.show();
    }

    /**
     * 启动图库选择器
     */
    private void startGalleryToGetImg(){
        mImagePicker.startGallery(this, new ImagePicker.Callback() {
            // 选择图片回调
            @Override public void onPickImage(Uri imageUri) {

            }

            // 裁剪图片回调
            @Override public void onCropImage(Uri imageUri) {
                mFile = FileUtil.uriToFile(mContext, imageUri);
                Glide.with(mContext)
                        .load(imageUri)
                        .into(mDBind.ivHead);
                mPresent.getAvatarUrlAddress(mFile);
            }

            // 自定义裁剪配置
            @Override public void cropConfig(CropImage.ActivityBuilder builder) {
                builder.setMultiTouchEnabled(false)
                        .setCropShape(CropImageView.CropShape.RECTANGLE)// 是否启动多点触摸
                        .setGuidelines(CropImageView.Guidelines.ON_TOUCH)// 设置网格显示模式
                        .setRequestedSize(480, 480)// 调整裁剪后的图片最终大小
                        .setAspectRatio(1, 1);// 宽高比
            }

            // 用户拒绝授权回调
            @Override public void onPermissionDenied(int requestCode, String[] permissions, int[] grantResults) {
            }
        });
    }

    /**
     * 启动照相机
     */
    private void startCameraToGetImg(){
        mImagePicker.startCamera(this, new ImagePicker.Callback() {
            // 选择图片回调
            @Override public void onPickImage(Uri imageUri) {

            }

            // 裁剪图片回调
            @Override public void onCropImage(Uri imageUri) {
                mFile = FileUtil.uriToFile(mContext, imageUri);
                Glide.with(mContext)
                        .load(imageUri)
                        .into(mDBind.ivHead);
                mPresent.getAvatarUrlAddress(mFile);
            }

            // 自定义裁剪配置
            @Override public void cropConfig(CropImage.ActivityBuilder builder) {
                builder.setMultiTouchEnabled(false)
                        .setCropShape(CropImageView.CropShape.RECTANGLE)// 是否启动多点触摸
                        .setGuidelines(CropImageView.Guidelines.ON_TOUCH)// 设置网格显示模式
                        .setRequestedSize(480, 480)// 调整裁剪后的图片最终大小
                        .setAspectRatio(1, 1);// 宽高比
            }

            // 用户拒绝授权回调
            @Override public void onPermissionDenied(int requestCode, String[] permissions, int[] grantResults) {
            }
        });
    }
}
